<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Selection extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->library('ion_auth');
		$this->load->library('session');
		$this->load->library('form_validation');
		$this->load->database();
		$this->load->helper(array('url','language'));
    $this->load->model('selections_model');
    $this->lang->load('general');
	}

  function index()
    {
        if($this->ion_auth->logged_in())
        {
            $this->data['user'] = $this->ion_auth->user()->row();

            $this->data['selection'] = $this->selections_model->get_by_user($this->data['user']->user_id);
            $this->data['replacements'] = $this->selections_model->get_replacements_by_user($this->data['user']->user_id);
                      

            $this->data['title'] = lang('selection');
            $this->data['view'] = 'selection';
            $this->load->view('template', $this->data);

        }
        else
        {
            redirect('account/login', 'refresh');
        }
    }

    function edit()
    {
      $this->data['title'] = lang('edit_selection');

      if (!$this->ion_auth->logged_in())
      {
        redirect('account/login', 'refresh');
      }

      if(tour_started()) // No more editing of teams!
      {
        redirect('selection');
      }

      $user = $this->ion_auth->user()->row();

      //validate form input
      // for ($i=1; $i < 16; $i++) { 
         $this->form_validation->set_rules('user', 'required');
      // }

      $this->data['selection'] = $this->selections_model->get_by_user($user->user_id);
      $this->data['replacements'] = $this->selections_model->get_replacements_by_user($user->user_id);

      if ($this->form_validation->run() == true)
      {
        $selection = $this->input->post('select_rider');
        $replacements = $this->input->post('replacement_rider');
        $sel_string = "";
        $rep_string = "";
        foreach($selection as $rider_id => $selected)
        {
          if($selected == 1)
          {
            $sel_string .= ",".$rider_id;
          }
        }
        foreach($replacements as $rider_id => $replacement)
        {
          if($replacement == 1)
          {
            $rep_string .= ",".$rider_id;
          }
        }
        $attributes['user_id'] = $user->id;
        $attributes['selection'] = trim($sel_string," ,");
        $attributes['replacements'] = trim($rep_string," ,");
        $this->selections_model->update($user->id, $attributes);
        redirect('selection/edit','refresh');

      }
      else
      { //display the result edit form
        //set the flash data error message if there is one

        //list the riders
        $this->load->model(array('teams_model', 'riders_model'));
        $this->load->helper('date');
        $this->data['teams'] = $this->teams_model->get_all();


        $i = 0;
        foreach($this->data['teams'] as $team)
        {
          $riders = $this->riders_model->get_by_team_number($team->team_number);
          $this->data['teams'][$i]->team_riders = $riders;
          $i++;
        }

        $this->load->helper('form');
        $current_selection = $this->selections_model->get_selection_only($user->id);
        if(is_object($current_selection))
        {
          $this->data['current_team'] = explode(',',$current_selection->selection);
          $this->data['current_replacements'] = explode(',',$current_selection->replacements);
        }
        else
        {
          $this->data['current_team'][] = 0;
          $this->data['current_replacements'][] = 0;

        }
        $this->data['user'] = $user;
        $this->data['help_message_title'] = 'help_selection_title';
        $this->data['help_message_text'] = 'help_selection_text';        
        $this->data['view'] = 'edit_selection';
        $this->load->view('template', $this->data);
      }
    }

    function ajax_save_selection()
    {
        $selection = $this->input->post('select_rider');
        $replacements = $this->input->post('replacement_rider');
        $user_id = $this->input->post('user');
        $sel_string = "";
        $rep_string = "";
        $sel_count = 1;
        $rep_count = 1;
        foreach($selection as $rider_id => $selected)
        {
          if($selected == 1 && $sel_count <= 20)
          {
            $sel_string .= ",".$rider_id;
            $sel_count++;
          }
        }
        foreach($replacements as $rider_id => $replacement)
        {
          if($replacement == 1 && $rep_count <= 5)
          {
            $rep_string .= ",".$rider_id;
            $rep_count++;
          }
        }
        $attributes['user_id'] = $user_id;
        $attributes['selection'] = trim($sel_string," ,");
        $attributes['replacements'] = trim($rep_string," ,");
        if(!tour_started())
        {
          $this->selections_model->update($user_id, $attributes);
        

          $selection = $this->selections_model->get_by_user($user_id);
          $replacements = $this->selections_model->get_replacements_by_user($user_id);
          $html =array('selections'=> "",'replacements' => "");
          foreach($selection as $rider)
          {
            if(is_object($rider))
            {
              $class= 'rider';
              if(!$rider->active)
              {
                $class.= " inactive";
              }
              $html['selections'] .= "<li class='".$class."'>".$rider->number." ".anchor('info/rider/'.$rider->rider_id,$rider->last_name." ".$rider->first_name)." (".anchor('info/team/'.$rider->team_number, $rider->team_shortname).")";
            }
            else
            {
              $html['selections'] = "<li>".lang('no_selection_yet')."</li>";
            }
          }
          foreach($replacements as $rider)
          {
            if(is_object($rider))
            {
              $class= 'rider';
              if(!$rider->active)
              {
                $class.= " inactive";
              }
              $html['replacements'] .= "<li class='".$class."'>".$rider->number." ".anchor('info/rider/'.$rider->rider_id,$rider->last_name." ".$rider->first_name)." (".anchor('info/team/'.$rider->team_number, $rider->team_shortname).")";
            }
            else
            {
              $html['replacements'] = "<li>".lang('no_selection_yet')."</li>";
            }
          }
          echo json_encode($html);
        }
        else
        {
          echo "Nononononono";
        }

    }
    
}    